//
//  ViewController.m
//  LessonUI_19_数据持久化
//
//  Created by 王佩 on 15/9/9.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "ViewController.h"
#import "Person.h"
#import "Dog.h"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
#pragma mark---获取沙盒下的Caches文件目录
    NSString * cachesPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;

#pragma mark---对复杂对象进行持久化
//  过程:(复杂对象->归档->NSSData->writeToFile)
    Person * person = [[Person alloc] init];
    Dog * dog = [[Dog alloc] init];
    dog.color = @"黄色";
    dog.breed = @"哈士奇";
    person.name = @"zhangsan";
    person.age = 20;
    person.dog = dog;
    
    NSMutableData * mutData = [NSMutableData data];
    //  创建归档器
    NSKeyedArchiver * archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:mutData];
    //  进行归档
    [archiver encodeObject:person forKey:@"person"];
    //  结束归档
    [archiver finishEncoding];
    //  将归档之后的NSData数据,写入文件
//    ①.存储路径
    NSString * personPath = [cachesPath stringByAppendingPathComponent:@"person.txt"];
    //  ②.根据路径写入文件
    [mutData writeToFile:personPath atomically:YES];
    NSLog(@"%@",personPath);
    NSLog(@"%@",mutData);
#pragma mark--从文件中读取复杂对象
//  过程:(读取文件->NSData->反归档->复杂对象)
    //  从文件中读取NSData数据
   NSData *  resultData = [NSData dataWithContentsOfFile:personPath];
    //  创建反归档工具
    NSKeyedUnarchiver * unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:resultData];
    //  使用反归档工具对resultData数据进行反归档
   Person * person1 = [unarchiver decodeObjectForKey:@"person"];
    //  结束反归档
    [unarchiver finishDecoding];
    //
    NSLog(@"%@,%@,%lu",person1.name,person1.dog.breed,person1.age);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
